<template>
  <div class="app-container">
    <el-row>
      <el-col :xs="24" class="table_big_bg">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                <el-form-item label="区域名称" prop="areaCode">
                  <treeselect @keyup.enter.native="handleQuery" v-model="queryParams.areaCode" :options="areaOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称"/>
                </el-form-item>
                <el-form-item label="集中器名称" prop="concentratorName">
                  <el-input
                    v-model="queryParams.concentratorName"
                    placeholder="请输入集中器名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="集中器地址" prop="concentratorId">
                  <el-input
                    v-model="queryParams.concentratorId"
                    placeholder="请输入集中器地址"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="SIM卡号码" prop="simNum">
                  <el-input
                    v-model="queryParams.simNum"
                    placeholder="请输入SIM卡号码"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8  padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:concentrator:add']"
            >新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['basedata:concentrator:edit']"
            >修改</el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:concentrator:remove']"
            >删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['basedata:concentrator:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="concentratorList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="设备归属水司" align="center" prop="tenantId" width="120"/> -->
          <!-- <el-table-column label="平台表单自增主键" align="center" prop="ID"/> -->
          <el-table-column label="区域" align="center" prop="areaName" width="120" v-if="columns[0].visible" :show-overflow-tooltip="true"/>//明天看
          <el-table-column label="集中器名称" align="center" prop="concentratorName" width="120" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="集中器地址" align="center" prop="concentratorId" width="120" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="集中器型号" align="center" prop="concentratorType" width="120" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="集中器版本" align="center" prop="concentratorVer" width="120" v-if="columns[4].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="协议类型" align="center" prop="protocolType" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="抄表日期" align="center" prop="readDate" v-if="columns[5].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="安装位置" align="center" prop="installAddress" v-if="columns[6].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="通讯类型" align="center" prop="communicationType" v-if="columns[8].visible" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="超时时间" align="center" prop="TimeOver" v-if="columns[9].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="IP地址" align="center" prop="ipAddress" v-if="columns[7].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="端口" align="center" prop="port" v-if="columns[8].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="网络接入点" align="center" prop="NetPoint" width="120" v-if="columns[12].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="心跳周期" align="center" prop="heartbeatCycle" v-if="columns[9].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="SIM卡号码" align="center" prop="simNum" width="120" v-if="columns[10].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="ccid" align="center" prop="ccid" v-if="columns[15].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="终端位置纬度" align="center" prop="lat" width="140" v-if="columns[11].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="终端位置经度" align="center" prop="lng" width="140" v-if="columns[12].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="终端位置经纬度" align="center" prop="Locate" width="160" v-if="columns[18].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="生产厂家" align="center" prop="supplierId" v-if="columns[13].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.concentrator_supplier" :value="scope.row.supplierId"/>
            </template>
          </el-table-column>
          <!-- <el-table-column label="备注" align="center" prop="remark" v-if="columns[20].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:concentrator:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:concentrator:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改集中器管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <el-form-item label="区域名称" prop="areaCode">
          <!-- <el-input v-model="form.areaCode" placeholder="请输入区域名称" /> -->
          <treeselect v-model="form.areaCode" :options="areaOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称" style="width:202px;"/>
        </el-form-item>
        <el-form-item label="集中器名称" prop="concentratorName">
          <el-input v-model="form.concentratorName" placeholder="请输入集中器名称" />
        </el-form-item>
        <el-form-item label="集中器地址" prop="concentratorId">
          <el-input v-model="form.concentratorId" placeholder="请输入集中器地址" />
        </el-form-item>
        <el-form-item label="集中器版本" prop="concentratorVer">
          <el-input v-model="form.concentratorVer" placeholder="请输入集中器版本" />
        </el-form-item>
        <el-form-item label="集中器型号" prop="concentratorType">
          <el-input v-model="form.concentratorType" placeholder="请输入集中器型号" />
        </el-form-item>
        <el-form-item label="厂家名称" prop="supplierId">
          <el-select v-model="form.supplierId" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="协议类型" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议类型" style="width: 202px" clearable>
            <el-option v-for="(item, index) of protocolOptionList" :key="index" :label="item.protocolName" :value="item.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抄表日期" prop="readDate">
          <el-input v-model.number="form.readDate" placeholder="请输入抄表日期" />
          <!-- <el-date-picker clearable
            v-model.number="form.readDate"
            type="datetime"
            placeholder="请选择抄表日期"
            style="width: 202px;"
            value-format="timestamp">
          </el-date-picker> -->
        </el-form-item>
        <!-- <el-form-item label="通讯类型" prop="communicationType">
          <el-input v-model="form.communicationType" placeholder="请输入通讯类型" />
        </el-form-item> -->
          <!-- <el-date-picker clearable
            v-model="form.TimeOver"
            type="datetime"
            placeholder="请选择超时时间"
            style="width: 202px;">
          </el-date-picker> -->
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口" />
        </el-form-item>
        <!-- <el-form-item label="网络接入点" prop="NetPoint">
          <el-input v-model="form.NetPoint" placeholder="请输入网络接入点" />
        </el-form-item> -->
        <el-form-item label="心跳周期" prop="heartbeatCycle">
          <el-input v-model.number="form.heartbeatCycle" placeholder="请输入心跳周期" />
        </el-form-item>
        <el-form-item label="SIM卡号码" prop="simNum">
          <el-input v-model="form.simNum" placeholder="请输入SIM卡号码" />
        </el-form-item>
        <!-- <el-form-item label="ccid" prop="ccid">
          <el-input v-model="form.ccid" placeholder="请输入ccid" />
        </el-form-item> -->
        <el-row>
          <el-form-item label="终端位置纬度" prop="lat">
            <el-input v-model="form.lat" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item label="终端位置经度" prop="lng">
            <el-input v-model="form.lng" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item>
            <i class="el-icon-location-information" style="color: #1890ff" @click="handleMap"></i>
          </el-form-item>
        </el-row>
        <el-form-item label="安装位置" prop="installAddress">
          <el-input v-model="form.installAddress" placeholder="请输入安装位置" />
        </el-form-item>
        <!-- <el-form-item label="终端位置经纬度" prop="Locate">
          <el-input v-model="form.Locate" placeholder="请输入终端位置经纬度" />
        </el-form-item> -->
        <!-- 超时时间需要注释 -->
        <!-- <el-form-item label="超时时间" prop="TimeOver">
          <el-input v-model="form.TimeOver" placeholder="请输入超时时间" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 定位对话框 -->
    <el-dialog
      width="700px"
      :title="mapdialog.title"
      :visible.sync="mapdialog.open"
      append-to-body
      @close="closeMapDialog"
      :destroy-on-close="true">
      <el-row class="line">
        <el-card shadow="never">
          <div id="mapContent" ref="mapContent"></div>
        </el-card>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="success" @click="initMap">获取当前位置</el-button> -->
        <el-button type="primary" @click="submitMap">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConcentrator, getConcentrator, delConcentrator, addConcentrator, updateConcentrator } from "@/api/record/concentrator";
import Treeselect from "@riophae/vue-treeselect";
import "highlight.js/styles/github-gist.css";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { gcj2bdString } from "@/utils/coordinate";
import { protocolOption } from '@/api/record/protocol'


export default {
  name: "Concentrator",
  dicts: ['default_position', 'concentrator_supplier'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 集中器管理表格数据
      concentratorList: [],
      // 协议下拉框
      protocolOptionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        concentratorName: null,
        concentratorType: null,
        concentratorId: null,
        protocolType: null,
        simNum: null,
      },
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '110px',
      // 列信息
      // 表单参数
      form: {
        tenantId: '710170'
      },
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "设备归属水司不能为空", trigger: "blur" }
        // ],
        areaCode: [
          { required: true, message: "区域名称不能为空", trigger: "blur" }
        ],
        concentratorName: [
          { required: true, message: "集中器名称不能为空", trigger: "blur" }
        ],
        concentratorId: [
          { required: true, message: "集中器地址不能为空", trigger: "blur" }
        ],
        protocolType: [
          { required: true, message: "协议类型不能为空", trigger: "change" }
        ],
        heartbeatCycle: [
         { type: 'number', message: '必须为数字'}
        ],
        readDate: [
          {type: 'number' , message: '必须为数字'}
        ],
        supplierId: [
          { required: true, message: "生产厂家不能为空", trigger: "change" }
        ]
      },
      // 列信息
      columns: [
        // { key: 0, label: `自增主键`, visible: false },
        // { key: 1, label: `用户归属水司`, visible: false },
        { key: 0, label: `区域`, visible: true },
        { key: 1, label: `集中器名称`, visible: true },
        { key: 2, label: `集中器地址`, visible: true },
        { key: 3, label: `集中器型号`, visible: true },
        // { key: 4, label: `集中器版本`, visible: true },
        { key: 4, label: `协议类型`, visible: true },
        { key: 5, label: `抄表日期`, visible: true },
        { key: 6, label: `安装位置`, visible: true },
        // { key: 8, label: `通讯类型`, visible: true },
        // { key: 9, label: `超时时间`, visible: true },
        { key: 7, label: `IP地址`, visible: true },
        { key: 8, label: `端口`, visible: true },
        { key: 9, label: `心跳周期`, visible: true },
        { key: 10, label: `SIM卡号码`, visible: true },
        { key: 11, label: `终端位置纬度`, visible: true },
        { key: 12, label: `终端位置经度`, visible: true },
        { key: 13, label: `生产厂家`, visible: true },
        // { key: 20, label: `备注`, visible: true },
      ],
      // 区域树选项
      areaOptions: [],
      // 地图
      map:{},
      // 定位弹窗参数
      mapdialog: {
        title: '定位',
        open: false,
      },
      // 位置
      position:{
        currentLat: '',
        currentLng: '',
        getLat: '',
        getLng: '',
        newformlng: '',
        newformlat: '',
        oldformlng: '',
        oldformlat: '',
        defaultPosition: []
      },
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
    this.getProtocolOption()
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  methods: {
    // 获取协议下拉框数据
    getProtocolOption(){
      protocolOption().then(response => {
        this.protocolOptionList = response.data
      })
    },
     //去掉children=null的属性
    normalizer(node){
      if(node.children==null || node.children=='null'){
        delete node.children;
      }
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        var obj = {
          id: item.areaCode,
          label: item.areaName,
          children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
        }
        this.areaOptions.push(obj)
      })
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 定位对话框打开
    handleMap(){
      this.mapdialog.title = '定位'
      this.mapdialog.open = true
      this.$nextTick(() => {
        this.initMap();
      })
    },
    // 定位对话框关闭
    closeMapDialog(){
      this.mapdialog.open = false
      this.map = new T.Map('mapContent');
    },
    // 初始化地图
    initMap(){
      let pickup;
      let this_ = this
      const init = new Promise((resolve, reject) => {
        if(window.T !== 'undefined') {
            resolve(window.T)
        }
      })
      mapContentinit.then(T => {
        this_.map = new T.Map('mapContent');
        this_.map.enableDrag()
        let point = new T.LngLat(this.dict.type.default_position[1].value, this.dict.type.default_position[0].value)
        this_.map.centerAndZoom(point, 12);
        this_.map.addOverLay(new T.Marker(point));
        this_.position.currentLat = this.dict.type.default_position[0].value
        this_.position.currentLng = this.dict.type.default_position[1].value
        let config = {
          callback: this_.getLngLat
        };
        pickup = new T.CoordinatePickup(this_.map, config); //获取当前鼠标点击位置的地理坐标
        pickup.addEvent();
      })
    },
    getLngLat(lnglat){
      const x = lnglat.lng;
      const y = lnglat.lat; //纵坐标纬度
      this.map.clearOverLays(); // 清空原来的标注点
      let point = new T.LngLat(x, y);
      let marker = new T.Marker(point);
      this.map.addOverLay(marker); // 添加标注点
      this.getGeocoderFun(x, y);
    },
    // 根据经纬度获取地址
    async getGeocoderFun(lng, lat) {
      let T = window.T;
      let geocoder = new T.Geocoder();
      geocoder.getLocation(new T.LngLat(lng, lat), (result) => {
        this.position.currentLng = lng
        this.position.currentLat = lat
      });
    },
    submitMap(){
      let mapType = 'GAODE'
      // this.gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
      let positionArr = gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
      this.form.lng = positionArr[0]
      this.form.lat = positionArr[1]
      this.mapdialog.open = false
    },

    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    /** 查询集中器管理列表 */
    getList() {
      this.loading = true;
      listConcentrator(this.queryParams).then(response => {
        this.concentratorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tenantId: '710170',
        ID: null,
        areaCode: null,
        concentratorName: null,
        concentratorId: null,
        concentratorType: null,
        concentratorVer: null,
        protocolId: null,
        readDate: null,
        installAddress: null,
        communicationType: null,
        TimeOver: null,
        ipAddress: null,
        port: null,
        NetPoint: null,
        heartbeatCycle: null,
        simNum: null,
        ccid: null,
        lat: null,
        lng: null,
        Locate: null,
        remark: null,
        supplierId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加集中器管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getConcentrator(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改集中器管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ID != null) {
            updateConcentrator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConcentrator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      this.$modal.confirm('是否确认删除集中器管理编号为"' + IDs + '"的数据项？').then(function() {
        return delConcentrator(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/concentrator/export', {
        ...this.queryParams
      }, `集中器_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
  .line{
    height: 500px;
    ::v-deep .el-card__body{
      width: 100%;
      height: 500px;
      background-color: white;
      padding: 0px 0px;
    }
  }
  #mapContent{
    width: 100%;
    margin: 0 auto;
    height: 500px;
  }
</style>
